package com.wuji.salary.common;


import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceGetcolumnvalRequest;
import com.dingtalk.api.response.OapiAttendanceGetcolumnvalResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.StringUtils;
import com.wuji.salary.entity.DingTalkAttendance;
import com.wuji.salary.entity.DingTalkAttendance2;
import org.springframework.context.annotation.ComponentScan;
import shade.com.alibaba.fastjson2.JSONArray;
import shade.com.alibaba.fastjson2.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.wuji.salary.common.GetAllUserId.getAllUserId;
import static com.wuji.salary.common.GetToken.token;
import static com.wuji.salary.common.GetUserInfo.getDeptName;
import static com.wuji.salary.common.GetUserInfo.getUserInfo;

/**
 *   根据 userId 获取钉钉考勤报表数据
 */
@ComponentScan
public class GetDingTalkAttendance {

    public static void main(String[] args) {
        getAttendance("","");
    }


    /**
     * 综合所有人的考勤数据返回
     */
    public static ArrayList<DingTalkAttendance> getAttendanceAll(String dateTime){
        ArrayList<DingTalkAttendance> list = new ArrayList<>();
        List<List<String>> lists = getAllUserId();
        System.out.println(lists);
        for (List<String> innerList : lists) {
            if (innerList == null) {
                continue;
            }
            for (String userId : innerList) {
                if (userId == null) {
                    continue;
                }
                DingTalkAttendance attendance = getAttendance(userId,dateTime);
                DingTalkAttendance2 attendance2 = getAttendance2(userId,dateTime);
                attendance.set_widget_1716358428405(attendance2.get_widget_1716358428405());
                attendance.set_widget_1716358428442(attendance2.get_widget_1716358428442());
                attendance.set_widget_1716358428461(attendance2.get_widget_1716358428461());
                attendance.set_widget_1716358428480(attendance2.get_widget_1716358428480());
                //根据userId去查询姓名 手机号 工号 部门
                OapiV2UserGetResponse.UserGetResponse response = getUserInfo(userId);
                attendance.setUserName(response.getName());
                attendance.setPhone(response.getMobile());
                response.setJobNumber(response.getJobNumber());
                attendance.setDeptName(getDeptName(response.getDeptIdList().get(0)));
                list.add(attendance);
            }
        }
        System.out.println(list);
        return list;
    }





    /**
     * 根据 userId 去查询一个人的考勤报表数据
     */
    public static DingTalkAttendance getAttendance(String userId,String dateTime){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
            OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
            //设置 userId
            req.setUserid(userId);
            //设置需要的报表数据
//            req.setColumnIdList("998315184,998315185,998315186,998315187,923202151,923202152,923202130,923202131,923202133,923202134,923202135,923202146,923202147,923202136,923202137,923202138,923202139,923202140,923202141,923202142");
            req.setColumnIdList("1084319783,1084319784,1084319762,1084319763,1084319765,1084319766,1084319767,1084319778,1084319779,1084319768,1084319769,1084319770,1084319771,1084319772,1084319773,1084319774,1107423181,1107423182,1107423183,1107423184");
            req.setFromDate(StringUtils.parseDateTime(dateTime));
//            req.setToDate(StringUtils.parseDateTime("2024-7-31 00:00:00"));
            req.setToDate(StringUtils.parseDateTime(calculateToDate(dateTime)));
            OapiAttendanceGetcolumnvalResponse rsp = client.execute(req, token);
            System.out.println(rsp.getBody());
            /**
             *   去进行统计
             */
            DingTalkAttendance dingTalkAttendance = test(rsp.getBody());
            return dingTalkAttendance;
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 针对考勤数据进行一个统计
     */
    public static DingTalkAttendance test(String aaa) {

        JSONObject jsonObject = JSONObject.parseObject(aaa);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray columnVals = result.getJSONArray("column_vals");

        //创建一个钉钉考勤对象
        DingTalkAttendance dingTalkAttendance = new DingTalkAttendance();
        // 加班总时长  24个字段
        int _widget_1716356765109 = dingTalkAttendance.get_widget_1716356765109();
        // 工作日（转加班费）
        int _widget_1716356765128 = dingTalkAttendance.get_widget_1716356765128();
        // 休息日（转加班费）
        int _widget_1716356765219 = dingTalkAttendance.get_widget_1716356765219();
        // 节假日（转加班费）
        int _widget_1716356765238 = dingTalkAttendance.get_widget_1716356765238();
        // 休息日加班
        int _widget_1716356765276 = dingTalkAttendance.get_widget_1716356765276();
        // 节假日加班
        int _widget_1716358427657 = dingTalkAttendance.get_widget_1716358427657();
        // 请假
        int _widget_1716358427954 = dingTalkAttendance.get_widget_1716358427954();
        // 应出勤天数
        int _widget_1716358427973 = dingTalkAttendance.get_widget_1716358427973();
        // 补卡次数
        int _widget_1716358427992 = dingTalkAttendance.get_widget_1716358427992();
        // 出勤天数
        int _widget_1716358428011 = dingTalkAttendance.get_widget_1716358428011();
        // 休息天数
        int _widget_1716358428030 = dingTalkAttendance.get_widget_1716358428030();
        // 工作时长
        int _widget_1716358428049 = dingTalkAttendance.get_widget_1716358428049();
        // 出差时长
        int _widget_1716358428068 = dingTalkAttendance.get_widget_1716358428068();
        // 外出时长
        int _widget_1716358428087 = dingTalkAttendance.get_widget_1716358428087();
        // 迟到次数
        int _widget_1716358428124 = dingTalkAttendance.get_widget_1716358428124();
        // 迟到时长
        int _widget_1716358428143 = dingTalkAttendance.get_widget_1716358428143();
        // 严重迟到次数
        int _widget_1716358428162 = dingTalkAttendance.get_widget_1716358428162();
        // 严重迟到时长
        int _widget_1716358428181 = dingTalkAttendance.get_widget_1716358428181();
        // 旷工迟到次数
        int _widget_1716358428330 = dingTalkAttendance.get_widget_1716358428330();
        // 早退次数
        int _widget_1716358428367 = dingTalkAttendance.get_widget_1716358428367();
        // 早退时长
        int _widget_1716358428386 = dingTalkAttendance.get_widget_1716358428386();

        for (Object columnVal : columnVals) {
            JSONObject columnValObject = (JSONObject) columnVal;
            JSONArray innerColumnVals = columnValObject.getJSONArray("column_vals");

            for (Object innerColumnVal : innerColumnVals) {
                JSONObject innerColumnValObject = (JSONObject) innerColumnVal;
                String value = innerColumnValObject.getString("value");

                if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1107423181) {//加班总时长
                    if (!value.equals("0.0")) {
                        _widget_1716356765109 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1107423182) {//工作日（转加班费)
                    if (!value.equals("0.0")) {
                        _widget_1716356765128 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1107423183) {//休息日（转加班费)
                    if (!value.equals("0.0")) {
                        _widget_1716356765219 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1107423184) {//节假日（转加班费)
                    if (!value.equals("0.0")) {
                        _widget_1716356765238 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319783) {//休息日加班
                    if (!value.equals("0.0")) {
                        _widget_1716356765276 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319784) {//节假日加班
                    if (!value.equals("0.0")) {
                        _widget_1716358427657 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319762) {//应出勤天数
                    if (!value.equals("0.0")) {
                        _widget_1716358427973 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319763) {//补卡次数
                    if (!value.equals("0.0")) {
                        _widget_1716358427992 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319765) {//出勤天数
                    if (!value.equals("0.0")) {
                        _widget_1716358428011 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319766) {//休息天数
                    if (!value.equals("0.0")) {
                        _widget_1716358428030 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319767) {//工作时长
                    if (!value.equals("0")) {
                        _widget_1716358428049 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319778) {//出差时长
                    if (!value.equals("0")) {
                        _widget_1716358428068 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319779) {//外出时长
                    if (!value.equals("0")) {
                        _widget_1716358428087 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319768) {//迟到次数
                    if (!value.equals("0")) {
                        _widget_1716358428124 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319769) {//迟到时长
                    if (!value.equals("0")) {
                        _widget_1716358428143 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319770) {//严重迟到次数
                    if (!value.equals("0")) {
                        _widget_1716358428162 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319771) {//严重迟到时长
                    if (!value.equals("0")) {
                        _widget_1716358428181 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319772) {//旷工迟到次数
                    if (!value.equals("0")) {
                        _widget_1716358428330 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319773) {//早退次数
                    if (!value.equals("0")) {
                        _widget_1716358428367 += Double.parseDouble(value);
                    }
                }else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319774) {//早退时长
                    if (!value.equals("0")) {
                        _widget_1716358428386 += Double.parseDouble(value);
                    }

                }
            }
        }
//        System.out.println("加班总时长为：" + _widget_1716356765109);
        dingTalkAttendance.set_widget_1716356765109(_widget_1716356765109);
//        System.out.println("工作日（转加班费）为：" + _widget_1716356765128);
        dingTalkAttendance.set_widget_1716356765128(_widget_1716356765128);
//        System.out.println("休息日（转加班费）为：" + _widget_1716356765219);
        dingTalkAttendance.set_widget_1716356765219(_widget_1716356765219);
//        System.out.println("节假日（转加班费）为：" + _widget_1716356765238);
        dingTalkAttendance.set_widget_1716356765238(_widget_1716356765238);
//        System.out.println("休息日加班为：" + _widget_1716356765276);
        dingTalkAttendance.set_widget_1716356765276(_widget_1716356765276);
//        System.out.println("节假日加班为：" + _widget_1716358427657);
        dingTalkAttendance.set_widget_1716358427657(_widget_1716358427657);
//        System.out.println("请假为：" + _widget_1716358427954);
        dingTalkAttendance.set_widget_1716358427954(_widget_1716358427954);
//        System.out.println("应出勤天数为：" + _widget_1716358427973);
        dingTalkAttendance.set_widget_1716358427973(_widget_1716358427973);
//        System.out.println("补卡次数为：" + _widget_1716358427992);
        dingTalkAttendance.set_widget_1716358427992(_widget_1716358427992);
//        System.out.println("出勤天数为：" + _widget_1716358428011);
        dingTalkAttendance.set_widget_1716358428011(_widget_1716358428011);
//        System.out.println("休息天数为：" + _widget_1716358428030);
        dingTalkAttendance.set_widget_1716358428030(_widget_1716358428030);
//        System.out.println("工作时长为：" + _widget_1716358428049);
        dingTalkAttendance.set_widget_1716358428049(_widget_1716358428049);
//        System.out.println("出差时长为：" + _widget_1716358428068);
        dingTalkAttendance.set_widget_1716358428068(_widget_1716358428068);
//        System.out.println("外出时长为：" + _widget_1716358428087);
        dingTalkAttendance.set_widget_1716358428087(_widget_1716358428087);
//        System.out.println("迟到次数为：" + _widget_1716358428124);
        dingTalkAttendance.set_widget_1716358428124(_widget_1716358428124);
//        System.out.println("迟到时长为：" + _widget_1716358428143);
        dingTalkAttendance.set_widget_1716358428143(_widget_1716358428143);
//        System.out.println("严重迟到次数为：" + _widget_1716358428162);
        dingTalkAttendance.set_widget_1716358428162(_widget_1716358428162);
//        System.out.println("严重迟到时长为：" + _widget_1716358428181);
        dingTalkAttendance.set_widget_1716358428181(_widget_1716358428181);
//        System.out.println("旷工迟到次数为：" + _widget_1716358428330);
        dingTalkAttendance.set_widget_1716358428330(_widget_1716358428330);
//        System.out.println("早退次数为：" + _widget_1716358428367);
        dingTalkAttendance.set_widget_1716358428367(_widget_1716358428367);
//        System.out.println("早退时长为：" + _widget_1716358428386);
        dingTalkAttendance.set_widget_1716358428386(_widget_1716358428386);
        return dingTalkAttendance;
    }

    /**
     * 根据 userId 去查询考勤报表数据2
     */
    public static DingTalkAttendance2 getAttendance2(String userId,String dateTime){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
            OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
            //设置 userId
            req.setUserid(userId);
            //设置需要的报表数据
//            req.setColumnIdList("923202143,923202144,923202145,923202168");
            req.setColumnIdList("1084319775,1084319776,1084319777,1084319800");
//            req.setFromDate(StringUtils.parseDateTime("2024-7-01 00:00:00"));
            req.setFromDate(StringUtils.parseDateTime(dateTime));
            req.setToDate(StringUtils.parseDateTime(calculateToDate(dateTime)));
            OapiAttendanceGetcolumnvalResponse rsp = client.execute(req, token);
            System.out.println(rsp.getBody());
            /**
             *   去进行统计
             */
            DingTalkAttendance2 dingTalkAttendance2 = test2(rsp.getBody());
            return dingTalkAttendance2;
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 针对考勤数据进行一个统计2
     */
    public static DingTalkAttendance2 test2(String aaa) {
        JSONObject jsonObject = JSONObject.parseObject(aaa);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray columnVals = result.getJSONArray("column_vals");

        //创建一个钉钉考勤对象
        DingTalkAttendance2 dingTalkAttendance2 = new DingTalkAttendance2();

        //上班缺卡次数
        int _widget_1716358428405 = dingTalkAttendance2.get_widget_1716358428405();
        // 下班缺卡次数
        int _widget_1716358428442 = dingTalkAttendance2.get_widget_1716358428442();
        // 旷工天数
        int _widget_1716358428461 = dingTalkAttendance2.get_widget_1716358428461();
        // 旷工迟到天数
        int _widget_1716358428480 = dingTalkAttendance2.get_widget_1716358428480();

        for (Object columnVal : columnVals) {
            JSONObject columnValObject = (JSONObject) columnVal;
            JSONArray innerColumnVals = columnValObject.getJSONArray("column_vals");

            for (Object innerColumnVal : innerColumnVals) {
                JSONObject innerColumnValObject = (JSONObject) innerColumnVal;
                String value = innerColumnValObject.getString("value");

                if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319775) {//上班缺卡次数
                    if (!value.equals("0")) {
                        _widget_1716358428405 += Double.parseDouble(value);
                    }
                } else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319776) {//下班缺卡次数
                    if (!value.equals("0")) {
                        _widget_1716358428442 += Double.parseDouble(value);
                    }
                } else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319777) {//旷工天数
                    if (!value.equals("0")) {
                        _widget_1716358428461 += Double.parseDouble(value);
                    }
                } else if (columnValObject.getJSONObject("column_vo").getInteger("id") == 1084319800) {//旷工迟到天数
                    if (!value.equals("0")) {
                        _widget_1716358428480 += Double.parseDouble(value);
                    }
                }
            }
        }
//        System.out.println("上班缺卡次数为：" + _widget_1716358428405);
        dingTalkAttendance2.set_widget_1716358428405(_widget_1716358428405);
//        System.out.println("下班缺卡次数为：" + _widget_1716358428442);
        dingTalkAttendance2.set_widget_1716358428442(_widget_1716358428442);
//        System.out.println("旷工天数为：" + _widget_1716358428461);
        dingTalkAttendance2.set_widget_1716358428461(_widget_1716358428461);
//        System.out.println("旷工迟到天数为：" + _widget_1716358428480);
        dingTalkAttendance2.set_widget_1716358428480(_widget_1716358428480);
        return dingTalkAttendance2;
    }
    /**
     * 动态计算出需要的考勤日期
     */
    public static String calculateToDate(String fromDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format.parse(fromDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            int month = calendar.get(Calendar.MONTH) + 1;
            int year = calendar.get(Calendar.YEAR);

            // 如果是当月，返回今天的日期
            if (month == Calendar.getInstance().get(Calendar.MONTH) + 1 && year == Calendar.getInstance().get(Calendar.YEAR)) {
                calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                return format.format(calendar.getTime());
            }

            calendar.set(Calendar.DAY_OF_MONTH, getLastDayOfMonth(month));
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            return format.format(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int getLastDayOfMonth(int month) {
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                if ((year % 4 == 0 && year % 100!= 0) || year % 400 == 0) {
                    return 29;
                } else {
                    return 28;
                }
            default:
                return -1;
        }
    }
}
